package com.hubing.cloud.app.web.aspect;

import com.alibaba.fastjson2.JSONObject;
import com.hubing.cloud.app.web.model.CodeMsg;
import com.hubing.cloud.app.web.model.GlobalException;
import com.hubing.cloud.app.web.model.ResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理
 */
@Slf4j
@Configuration
@ControllerAdvice(basePackages = "com.hubing.cloud.app.web")
public class GlobalExceptionAspect {

	/**
	 * 给有友好异常信息
	 *
	 * 如捕捉异常类型过多且处理不一，分开方法写
	 * 建议大部分可预见异常可以走CodeMsg
	 *
	 * @throws Exception
	 */
	@ExceptionHandler
	@ResponseBody
	public Object exceptionHandler(HttpServletRequest request, Exception e) {
		ResponseBean result = null;

		if (e instanceof GlobalException) {
			GlobalException ex = (GlobalException) e;
			result =  ResponseBean.error(ex.getCm());
		} else if (e instanceof BindException) {
			BindException ex = (BindException) e;
			FieldError fieldError = ex.getBindingResult().getFieldError();
			assert fieldError != null;
			result = ResponseBean.error(CodeMsg.BIND_ERROR.fillArgs(fieldError.getDefaultMessage()));
			log.info("{}:{}", fieldError.getField(), fieldError.getDefaultMessage());
		} else if (e instanceof MethodArgumentNotValidException) {
			MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
			FieldError fieldError = ex.getBindingResult().getFieldError();
			result = ResponseBean.error(CodeMsg.BIND_ERROR.fillArgs(fieldError.getDefaultMessage()));
			log.info("{}:{}", fieldError.getField(), fieldError.getDefaultMessage());
		} else {
			log.error("Exception:{}", e.getMessage());
			e.printStackTrace();
			result = ResponseBean.error(CodeMsg.SERVER_ERROR);
		}
		log.info("[exception] [ url={} ] [ ip={} ] [param={}]",
				request.getRequestURI(), request.getRemoteAddr(), e);

		return result;
	}

}